package cc.wsyw126.java.collection.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by junpeng.yang on 16/8/31.
 */
public class TestThreadSafe {
    public CopyOnWriteArrayList<Integer> getCopyOnWriteArrayList(int n){
        long start = System.currentTimeMillis();
        CopyOnWriteArrayList<Integer> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
        for (int i = 0; i < n; i++) {
            copyOnWriteArrayList.add(i);
        }
        System.out.println("TestThreadSafe.getCopyOnWriteArrayList  :  " + (System.currentTimeMillis() - start));
        return copyOnWriteArrayList;
    }

    public Vector<Integer> getVector(int n){
        long start = System.currentTimeMillis();
        Vector<Integer> vector = new Vector<>();
        for (int i = 0; i < n; i++) {
            vector.add(i);
        }
        System.out.println("TestThreadSafe.getVector  :  " + (System.currentTimeMillis() - start));
        return vector;
    }

    public List<Integer> getSafeArrayList(int n){
        long start = System.currentTimeMillis();
        List<Integer> arrayList = Collections.synchronizedList(new ArrayList<Integer>());
        for (int i = 0; i < n; i++) {
            arrayList.add(i);
        }
        System.out.println("TestThreadSafe.getSafeArrayList  :  " + (System.currentTimeMillis() - start));
        return arrayList;
    }

    public static void main(String[] args) {
        TestThreadSafe testThreadSafe = new TestThreadSafe();
        int n =100000;
        testThreadSafe.getCopyOnWriteArrayList(n);
        testThreadSafe.getVector(n);
        testThreadSafe.getSafeArrayList(n);
    }

}
